﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using WebMovil.Base;

namespace WebMovil
{
    public class IISHandler1 : IHttpHandler
    {
        /// <summary>
        /// You will need to configure this handler in the web.config file of your 
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members

        public bool IsReusable
        {
            // Return false in case your Managed Handler cannot be reused for another request.
            // Usually this would be false in case you have some state information preserved per request.
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string id = context.Request.QueryString["Id"];
            if (id != null)
            {
                context.Response.ContentType = "image/jpeg";
                Stream strm = ShowEmpImage(id);
                byte[] buffer = new byte[4096];
                int byteSeq = strm.Read(buffer, 0, 4096);
                while (byteSeq > 0)
                {
                    context.Response.OutputStream.Write(buffer, 0, byteSeq);
                    byteSeq = strm.Read(buffer, 0, 4096);
                }
            }
        }
        private Stream ShowEmpImage(string id)
        {

            var db = new DataClasses1DataContext();
            var r = (from a in db.MaestroArticulos where a.IdMaestroArticulo.ToString() == id select a).First();
            return new MemoryStream(r.Foto.ToArray());
        }

        #endregion
    }
}
